package vip.aster.system.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.tags.Tag;
import jakarta.validation.Valid;
import lombok.AllArgsConstructor;
import org.springdoc.core.annotations.ParameterObject;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;
import vip.aster.common.exception.BusinessException;
import vip.aster.common.utils.PageInfo;
import vip.aster.common.utils.ResultInfo;
import vip.aster.framework.i18n.MessageUtils;
import vip.aster.framework.log.annotation.Log;
import vip.aster.framework.log.enums.BusinessTypeEnum;
import vip.aster.framework.security.entity.SecurityUser;
import vip.aster.framework.security.entity.UserDetail;
import vip.aster.system.entity.SysRole;
import vip.aster.system.query.SysRoleQuery;
import vip.aster.system.query.SysUserRoleQuery;
import vip.aster.system.service.*;
import vip.aster.system.vo.SysMenuVO;
import vip.aster.system.vo.SysRoleOrgVO;
import vip.aster.system.vo.SysRoleVO;
import vip.aster.system.vo.SysUserVO;

import java.util.List;

/**
 * 角色管理
 *
 * @author Aster
 * @since 2023/12/8 10:02
 */
@Tag(name = "角色管理")
@RestController
@RequestMapping("/sys/role")
@AllArgsConstructor
public class SysRoleController {
    private SysRoleService sysRoleService;
    private SysMenuService sysMenuService;
    private SysUserService sysUserService;
    private SysRoleMenuService sysRoleMenuService;
    private SysRoleOrgService sysRoleOrgService;
    private SysUserRoleService sysUserRoleService;

    @GetMapping("/page")
    @Operation(summary = "分页")
    @Log(type = BusinessTypeEnum.SEARCH)
    @PreAuthorize("hasAuthority('sys:role:list')")
    public ResultInfo<PageInfo<SysRoleVO>> page(@ParameterObject SysRoleQuery query) {
        PageInfo<SysRoleVO> page = sysRoleService.pageList(query);
        return ResultInfo.success(page);
    }

    @GetMapping("/list")
    @Operation(summary = "列表")
    @Log(type = BusinessTypeEnum.SEARCH)
    @PreAuthorize("hasAuthority('sys:role:list')")
    public ResultInfo<List<SysRoleVO>> list() {
        LambdaQueryWrapper<SysRole> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.orderByAsc(SysRole::getSort);
        List<SysRole> list = sysRoleService.list(queryWrapper);
        return ResultInfo.success(SysRoleVO.convertList(list));
    }

    @GetMapping("/info/{id}")
    @Operation(summary = "信息")
    @Log(type = BusinessTypeEnum.SEARCH)
    @PreAuthorize("hasAuthority('sys:role:info')")
    public ResultInfo<SysRoleVO> info(@PathVariable("id") String id) {
        SysRole entity = sysRoleService.getById(id);
        if (entity == null) {
            throw new BusinessException(MessageUtils.message("role.info.null"));
        }
        // 转换对象
        SysRoleVO role = new SysRoleVO(entity);

        // 查询角色对应的菜单
        List<String> menuIdList = sysRoleMenuService.getMenuIdList(id);
        role.setMenuIdList(menuIdList);

        // 查询角色对应的数据权限
        List<String> orgIdList = sysRoleOrgService.getOrgIdList(id);
        role.setOrgIdList(orgIdList);

        return ResultInfo.success(role);
    }

    @PostMapping("/save")
    @Operation(summary = "保存")
    @Log(type = BusinessTypeEnum.SAVE)
    @PreAuthorize("hasAnyAuthority('sys:role:add', 'sys:role:edit')")
    public ResultInfo<String> save(@RequestBody @Valid SysRoleVO vo) {
        sysRoleService.save(vo);
        return ResultInfo.success();
    }

    @PostMapping("/delete")
    @Operation(summary = "删除")
    @Log(type = BusinessTypeEnum.DELETE)
    @PreAuthorize("hasAuthority('sys:role:delete')")
    public ResultInfo<String> delete(@RequestBody List<String> idList) {
        sysRoleService.delete(idList);
        return ResultInfo.success();
    }

    @PostMapping("/org")
    @Operation(summary = "数据权限")
    @Log(type = BusinessTypeEnum.UPDATE)
    @PreAuthorize("hasAuthority('sys:role:update')")
    public ResultInfo<String> dataScope(@RequestBody @Valid SysRoleOrgVO vo) {
        sysRoleService.updateOrg(vo);
        return ResultInfo.success();
    }

    @GetMapping("/menu")
    @Operation(summary = "角色菜单")
    @PreAuthorize("hasAuthority('sys:role:menu')")
    public ResultInfo<List<SysMenuVO>> menu() {
        UserDetail user = SecurityUser.getUser();
        List<SysMenuVO> list = sysMenuService.getUserMenuList(user, null);

        return ResultInfo.success(list);
    }

    @GetMapping("/user/page")
    @Operation(summary = "角色用户-分页")
    @PreAuthorize("hasAuthority('sys:role:list')")
    public ResultInfo<PageInfo<SysUserVO>> userPage(@ParameterObject SysUserRoleQuery query) {
        PageInfo<SysUserVO> page = sysUserService.roleUserPage(query);
        return ResultInfo.success(page);
    }

    @PostMapping("/user/delete/{roleId}")
    @Operation(summary = "删除角色用户")
    @Log(type = BusinessTypeEnum.DELETE)
    @PreAuthorize("hasAuthority('sys:role:delete')")
    public ResultInfo<String> userDelete(@PathVariable("roleId") String roleId, @RequestBody List<String> userIds) {
        sysUserRoleService.deleteByUserIdList(roleId, userIds);
        return ResultInfo.success();
    }

    @PostMapping("/user/save/{roleId}")
    @Operation(summary = "分配角色给用户列表")
    @Log(type = BusinessTypeEnum.DELETE)
    @PreAuthorize("hasAuthority('sys:role:user')")
    public ResultInfo<String> userSave(@PathVariable("roleId") String roleId, @RequestBody List<String> userIds) {
        sysUserRoleService.saveUserList(roleId, userIds);

        return ResultInfo.success();
    }
}
